﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;

namespace CSConsoleTest
{
    class TestSerialize : BaseConsoleTest
    {
        public void printDescription()
        {
            Console.WriteLine("--- Serialize ---");
        }

        public void doTest()
        {
            string testFilePath = "D:\\temp\\serialize_test.dat";

            FileStream targetStream = new FileStream(testFilePath, FileMode.OpenOrCreate);
            CanSerialize serializeObj = new CanSerialize() { Name = "TestSerializeMan", Number = 999, Secret = 123 };
            Console.WriteLine("Serialization target {0}", serializeObj);
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(targetStream, serializeObj);
            targetStream.Close();

            FileStream readStream = new FileStream(testFilePath, FileMode.Open);
            CanSerialize deserializedObj = (CanSerialize)formatter.Deserialize(readStream);

            Console.WriteLine("Deserialized target {0}", deserializedObj);
        }
    }

    class CanNotSerialize
    {
        private int secret;

        public CanNotSerialize()
        {
            secret = 0;
        }

        public int Secret { get; set; }

        public override string ToString()
        {
            return secret.ToString();
        }
    }

    [Serializable]
    class CanSerialize
    {
        [NonSerialized]
        private CanNotSerialize secret;

        public CanSerialize()
        {
            secret = new CanNotSerialize();
        }

        public int Number { get; set; }
        public string Name { get; set; }
        public int Secret
        {
            get
            {
                return secret.Secret;
            }
            set
            {
                secret.Secret = value;
            }
        }

        public override string ToString()
        {
            return "Name : " + Name + " Number : " + Number + " Secret : " + secret;
        }

    }
}
